"""
WSGI接口实现
"""
import logging

import pymysql
import json

# 定义一个全局路由表字典
route_table = {}


# 定义一个装饰器函数
def router(url):
    def wrapper(func):
        def inner():
            return func()
        route_table[url] = inner
        return inner

    return wrapper


@router('/index.html')
def index():
    with open('templates/index.html', 'r+', encoding='utf-8') as f:
        content = f.read()
    # 用%s占位
    row_str = """
            <tr>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>
                    <input type="button" value="添加" id="toAdd" name="toAdd" systemidvalue="%s">
                </td>
            </tr>
             """
    # 读取数据库
    connect = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stock_db',
                              charset='utf8')
    cur = connect.cursor()
    sql_str = "SELECT * FROM stock_db.info;"
    cur.execute(sql_str)
    result = cur.fetchall()
    cur.close()
    connect.close()

    # 多准备几条
    all_data = ''
    for t in result:
        all_data += row_str % (t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[1])

    # 将准备好的数据,替换到模板文件内容中的占位符上去  {%content%}
    # 注意,替换完成后,要将替换后的数据返回,因为字符串是一个不可变对象,所以在这里要接收一下替换后的数据
    content = content.replace('{%content%}', all_data)
    return content


@router('/center.html')
def center():
    with open('templates/center.html', 'r', encoding='utf-8') as f:
        content = f.read()
    content = content.replace('{%content%}', '')
    return content


@router('/center_data.html')
def center_data():
    """返回json数据"""
    connect = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stock_db',
                              charset='utf8')
    cur = connect.cursor()
    sql_str = """SELECT i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info \
    FROM stock_db.info AS i INNER JOIN stock_db.focus AS f ON i.id = f.info_id;"""
    cur.execute(sql_str)
    result = cur.fetchall()
    cur.close()
    connect.close()

    json_data = []
    for t in result:
        json_data_dict = {
            'code': t[0],
            'short': t[1],
            'chg': t[2],
            'turnover': t[3],
            'price': str(t[4]),
            'highs': str(t[5]),
            'note_info': t[6]
        }
        json_data.append(json_data_dict)
    # 将列表转换为JSON数据，且不使用ASCII对数据编码
    json_str = json.dumps(json_data, ensure_ascii=False)
    return json_str


def other():
    return '<h1>Page Not Found!</h1>'


def application(environ, start_response):
    request_url = environ['path']

    if request_url in route_table:
        # 准备响应状态码
        status = '200 OK'
        data = route_table[request_url]()
        logging.info(f'响应动态页面{request_url}成功')
    else:
        status = '404 Not Found'
        data = other()
        logging.info(f'响应动态页面{request_url}失败')

    # 执行回调函数，返回响应头和响应状态
    start_response(status, [('Server', 'PMWS2.0'), ('Content-Type', 'text/html;charset=utf-8')])
    return data
